package cn.lingyangwl.agile.common.datasource;

import cn.lingyangwl.agile.model.constants.TenantCons;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author shenguangyang
 */
@Slf4j
@Component
@RabbitListener(bindings = {
        @QueueBinding(
            // 切记: 此处无需设置队列名称，否在得话，多个消费者只有一个消费者能消费数据。其它消费者无法消费数据
            value = @Queue(durable = "true"),
            exchange = @Exchange(value = TenantDeleteMQ.EXCHANGE, type = ExchangeTypes.FANOUT))
})
public class TenantDeleteListener {

    @Resource
    private CommonService commonService;

    @RabbitHandler
    public void onMessage(@Payload String msg, Channel channel, Message message) {
        log.info("listener delete tenant, msg: {}", msg);
        TenantDeleteMQ.MsgPayload tenantDelete = TenantDeleteMQ.parse(msg, TenantDeleteMQ.MsgPayload.class);
        if (Objects.isNull(tenantDelete.getTenantId())) {
            return;
        }
        if (TenantCons.SYSTEM_TENANT_ID.compareTo(tenantDelete.getTenantId()) == 0) {
            return;
        }
        commonService.deleteAllDataByTenantId(tenantDelete.getIsMainTenant(), tenantDelete.getTenantId());
    }
}
